<?php
namespace App\Utils;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtToken
{
    /**
     * 生成jwt token
     */
    public static function encode(array $data, $key = '', $expire = 604800) : string
    {
        $token = [
            'data' => $data,
            'iss' => env('APP_NAME', 'hyperf'),
            'iat' => time(),
            'exp' => time() + $expire
        ];
        if (empty($key)) $key = env('APP_NAME', 'hyperf').'-key';
        return JWT::encode($token, $key, 'HS256');
    }

    /**
     * 解密jwt token
     */
    public static function decode(string $token, $key = '')
    {
        // $type = Config::get('jwt.jwt_type');
        // $key = Config::get('jwt.jwt_key');
        if (empty($key)) $key = env('APP_NAME', 'hyperf').'-key';
        $data = json_decode(json_encode(JWT::decode($token, new Key($key,'HS256'), ['HS256'])), true);
        return $data;
    }
}